<?php


namespace api\modules\v1\controllers;

use common\models\member\Member;
use Yii;
use common\helpers\CommonHelper;
use common\factory\DingtalkFactory;
use services\api\AccessTokenService;
use api\controllers\OnAuthController;
use api\modules\v1\forms\dingtalk\LoginForm;
use api\modules\v1\forms\dingtalk\DingtalkForm;

class DingtalkController extends OnAuthController
{
    public $modelClass = '';

    public $optional = ['fast-login'];

    public $optionalLimit = ['fast-login'];

    /**
     * @api {get} /v1/dingtalk/bind 用户绑定钉钉
     * @apiName bind
     * @apiGroup Dingtalk
     *
     * @apiParam {String} code                      临时授权码
     *
     * @apiSuccess {String} code                    状态码
     * @apiSuccess {String} message                 提示信息
     * @apiSuccess {Object} data                    返回内容
     * @apiSuccess {String} data.member_id          用户ID
     *
     */
    public function actionBind()
    {
        $param = Yii::$app->request->get();
        $param['member_id'] = Yii::$app->user->identity->member_id;

        // 获取用户信息
        /*[
            'errcode' => 0,
            'errmsg' => ok,
            'user_info' => [
                'nick' => '马小强',
                'unionid' => 'D0RdgtGjnW5734gR4bnt3giEiE',
                'dingId' => '$:LWCP_v1:$CW8fMV5h3eUSlQRC5ofyBg==',
                'openid' => 'MjVHxISDYH1QZpJJt6WMGwiEiE',
                'main_org_auth_high_level' => 1,
            ]
        ]*/
        $app = DingtalkFactory::createApp();
        $user = $app->oauth->use('app-01')->stateless()->user();

        if ($user['errcode'] != 0) {
            return CommonHelper::api(422, $user['errmsg']);
        }

        $model = new DingtalkForm();
        $model->setScenario('bind');
        $model->attributes = [
            'ding_unionid' => $user['user_info']['unionid'] ?? '',
            'ding_openid' => $user['user_info']['openid'] ?? '',
        ];
        if (!$model->validate()) {
            // 返回数据验证失败
            return CommonHelper::api(422, $this->getError($model));
        }

        return Yii::$app->services->member->bindDingtalk($model);
    }

    /**
     * @api {get} /v1/dingtalk/unbind 用户解绑钉钉
     * @apiName unbind
     * @apiGroup Dingtalk
     *
     */
    public function actionUnbind()
    {
        $member_id = Yii::$app->user->identity->member_id;
        $model = Member::findOne($member_id);
        $model->ding_unionid ='';
        $model->ding_openid = '';

        if ($model->save())
        {
            return CommonHelper::api(200, '解绑成功');
        }
        return CommonHelper::api(422, '解绑失败');
    }

    /**
     * @api {get} /v1/dingtalk/fast-login 钉钉快速登录【js渲染二维码，跳转前端页，获取code】
     * @apiName fast-login
     * @apiGroup Dingtalk
     *
     * @apiDescription 登录完成调用/v1/member/permissions,获取用户权限信息
     *
     * @apiParam {String} code                      临时授权码
     *
     * @apiSuccess {String} code                    状态码
     * @apiSuccess {String} message                 提示信息
     * @apiSuccess {Object} data                    返回内容
     * @apiSuccess {String} data.access_token       token令牌
     * @apiSuccess {Object} data.info               用户信息
     * @apiSuccess {Number} data.info.member_id     用户ID
     * @apiSuccess {String} data.info.username      用户名
     * @apiSuccess {String} data.info.realname      真实姓名
     * @apiSuccess {String} data.info.email         邮箱
     * @apiSuccess {String} data.info.mobile        手机号
     * @apiSuccess {Number} data.info.is_super      是否超管【1是、0否】
     * @apiSuccess {Number} data.info.project_id    默认项目ID
     *
     */
    public function actionFastLogin()
    {
        // 获取用户信息
        $app = DingtalkFactory::createApp();
        $user = $app->oauth->use('app-01')->stateless()->user();

        if ($user['errcode'] != 0) {
            return CommonHelper::api(422, $user['errmsg']);
        }

        $model = new LoginForm();
        $model->setScenario('fast_login');
        $model->attributes = [
            'ding_unionid' => $user['user_info']['unionid'] ?? '',
        ];
        if (!$model->validate()) {
            // 返回数据验证失败
            return CommonHelper::api(422, $this->getError($model));
        }

        $accessTokenService = new AccessTokenService();
        return $accessTokenService->getAccessToken($model->getMember());
    }

    /*public function actionTest()
    {
        // 获取用户信息
        $app = DingtalkFactory::createApp();

        // 扫码登录第三方网站
        $response = $app->oauth->use('app-01')->withQrConnect()->redirect();
        return $response;
    }*/
}
